<template>
    <el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item prop="carCode">
				<el-input v-model="state.queryForm.carCode" placeholder="请输入车辆编码" clearable style="width: 200px"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="getDataList()">查询</el-button>
			</el-form-item>
            <el-form-item>
                <el-button icon="RefreshRight" @click="reset(queryRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <!-- 地图卡片 -->
    <el-card header="车辆位置分布" style="margin-bottom: 20px">
        <div ref="mapContainer" style="height: 400px"></div>
    </el-card>

    <el-card>
        <el-space>
            <el-space>
                <el-button icon="Plus" type="primary" @click="addOrUpdateHandle()">新增</el-button>
            </el-space>
            <el-space>
                <el-button plain icon="Download" @click="downloadHandle('/ss/car/export')">导出</el-button>
            </el-space>
            <el-space>
                <el-button icon="Delete" plain type="danger" @click="deleteBatchHandle()">批量删除</el-button>
            </el-space>
        </el-space>

        <el-table v-loading="state.dataListLoading" :data="state.dataList" border class="layout-table"
            show-overflow-tooltip @selection-change="selectionChangeHandle">
            <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
            <el-table-column prop="carTypeId" label="车辆类型" header-align="center" align="center"></el-table-column>
            <el-table-column prop="carCode" label="车辆编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="carCodeUrl" label="车辆编码二维码" header-align="center" align="center">
                <template #default="scope">
                    <el-image v-if="scope.row.carCodeUrl" :src="scope.row.carCodeUrl"
                        :preview-src-list="[scope.row.carCodeUrl]" fit="cover"
                        style="width: 50px; height: 50px;"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="scenic" label="景区" header-align="center" align="center"></el-table-column>
            <el-table-column prop="carStatus" label="车辆状态" header-align="center" align="center">
                <template #default="scope">
                    <span>
                        {{ formatCarStatus(scope.row.carStatus) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="carPosition" label="车辆位置" header-align="center" align="center"></el-table-column>
            <el-table-column prop="carLockStatus" label="车辆是否上锁" header-align="center" align="center">
                <template #default="scope">
                    <span>
                        {{ formatLockStatus(scope.row.carLockStatus) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="powerStatus" label="电源状态" header-align="center" align="center">
                <template #default="scope">
                    <span>
                        {{ formatPowerStatus(scope.row.powerStatus) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
                <template #default="scope">
                    <el-dropdown trigger="click" @command="handleCommand($event, scope.row)">
                        <el-button type="primary" link>
                            操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="unlock">开锁</el-dropdown-item>
                                <el-dropdown-item command="horn">鸣笛</el-dropdown-item>
                                <el-dropdown-item command="changeScenic">更换景区</el-dropdown-item>
                                <el-dropdown-item command="setCarStatus">设置车辆状态</el-dropdown-item>
                                <el-dropdown-item command="setRunStatus">设置运行状态</el-dropdown-item>
                                <el-dropdown-item command="delete" divided type="danger">删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination :current-page="state.page" :page-sizes="state.pageSizes" :page-size="state.limit"
            :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle">
        </el-pagination>

        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateRef" v-model:visible="addOrUpdateVisible"
            @refreshDataList="getDataList"></add-or-update>
    </el-card>
</template>

<script setup lang="ts" name="SsCarIndex">
import { ref, reactive, onMounted, nextTick, h } from 'vue'
import { useCrud } from '@/hooks'
import { IHooksOptions } from '@/hooks/interface'
import AddOrUpdate from './add-or-update.vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useSsScenicLabelApi } from '@/api/scenic/scenic'

import {
    ElMessageBox,
    ElMessage,
    ElSelect,
    ElOption
} from 'element-plus'
import {
    getCarListApi,
    changeScenicApi,
    setCarStatusApi,
    setRunStatusApi,
    unlockCarApi,
    hornCarApi
} from '@/api/order/car'
import { ArrowDown } from '@element-plus/icons-vue'

interface ScenicOption {
  id: string | number;
  name: string;
}


interface CustomWindow extends Window {
    _AMapSecurityConfig?: {
        securityJsCode: string;
    };
}
// 高德地图安全配置
(window as CustomWindow)._AMapSecurityConfig = {
    securityJsCode: '627ad5369b5180f5607a1ef6a7371495'
}

// 响应式变量
const mapContainer = ref<HTMLDivElement | null>(null)
const mapInstance = ref<any>(null)
const markers = ref<any[]>([])
const map = ref<any>(null) // 地图实例

// 地图加载
const loadMap = () => {
    AMapLoader.load({
        key: 'e45796d0ec933e587f632e1cc6b4fd0e',
        version: '2.0',
        plugins: ['AMap.Marker', 'AMap.InfoWindow'],
    }).then((AMap) => {
        mapInstance.value = new AMap.Map(mapContainer.value!, {
            zoom: 12,
            viewMode: '2D'
        })

        // 在地图加载后直接添加固定坐标点
        map.value = AMap;
        addFixedMarkers()
        // setInterval(() => {
        // 	addFixedMarkers
        // }, 10000);
    }).catch(e => {
        console.error('地图加载失败', e)
    })
}


const formatLockStatus = (status: number) => {
    switch (status) {
        case 0:
            return '未上锁';
        case 1:
            return '已上锁';
        default:
            return '未知状态';
    }
}
const formatPowerStatus = (status: number) => {
    switch (status) {
        case 0:
            return '电量充足';
        case 1:
            return '电量低';
        case 2:
            return '正在充电';
        case 3:
            return '电量耗尽';
        default:
            return '未知状态';
    }
}


const formatCarStatus = (status: number) => {
    switch (status) {
        case 0:
            return '空闲';
        case 1:
            return '骑行中';
        case 2:
            return '故障中';
        case 3:
            return '充电中';
        default:
            return '未知状态';
    }
}


// 添加固定坐标点
const addFixedMarkers = () => {
    getCarListApi(
        {
            "scenicId": "",
            "carNo": ""
        }
    ).then(res => {
        const fixedLocations = new Array
        res.data.forEach((item: any) => {
            console.log('车辆位置', item.position)

            switch (item.carStatus) {
                case 0:
                    item.carStatus = '空闲';
                case 1:
                    item.carStatus = '骑行中';
                case 2:
                    item.carStatus = '故障中';
                case 3:
                    item.carStatus = '充电中';
                default:
                    item.carStatus = '未知状态';
            }


            fixedLocations.push({
                position: item.carPosition.split(',').map(Number), // 坐标,
                title: item.carCode, // 车辆名称,
                status: item.carStatus, // 车辆状态,
                icon: ''
            })
        })

        fixedLocations.forEach(location => {
            const markerIcon = new map.value.Icon({
                size: new map.value.Size(25, 25), // 图标大小
                image: location.icon, // 图标地址
                imageSize: new map.value.Size(25, 25) // 图标显示大小
            })

            const marker = new map.value.Marker({
                position: location.position,
                icon: markerIcon,
                offset: new map.value.Pixel(-12, -12) // 图标偏移
            })

            // 添加鼠标悬停事件
            marker.on('mouseover', (e: any) => {
                const infoWindow = new map.value.InfoWindow({
                    content: `
          <div style="padding:10px;background-color:white;border-radius:5px;box-shadow:0 0 10px rgba(0,0,0,0.2)">
            <strong>车辆名称:</strong> ${location.title}<br/>
            <strong>状态:</strong> ${location.status}
          </div>
        `,
                    offset: new map.value.Pixel(0, -30)
                })
                infoWindow.open(mapInstance.value, e.target.getPosition())
            })

            marker.setMap(mapInstance.value)
            markers.value.push(marker)
        })

        // 自适应视图
        mapInstance.value.setFitView(markers.value)

    })
}



// 状态管理
const state: IHooksOptions = reactive({
    dataListUrl: '/ss/car/page',
    deleteUrl: '/ss/car',
    queryForm: {
        carCode: ''
    },
    dataList: [],
    page: 1,
    limit: 10,
    total: 0,
    pageSizes: [10, 20, 50, 100]
})

// 引用
const queryRef = ref()
const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref()

// 新增/修改处理
const addOrUpdateHandle = (id?: number) => {
    addOrUpdateVisible.value = true
    nextTick(() => addOrUpdateRef.value.init(id))
}

const scenicOptions = ref<ScenicOption[]>([]);
const carStatusOptions = [
    { label: '空闲', value: 0 },
    { label: '骑行中', value: 1 },
    { label: '故障中', value: 2 },
    { label: '充电中', value: 3 }
]
const runStatusOptions = [
    { label: '正常运行', value: 0 },
    { label: '暂停服务', value: 1 },
    { label: '维护中', value: 2 }
]






const handleCommand = (command: string, row: any) => {
    switch (command) {
        case 'changeScenic':
            useSsScenicLabelApi().then(res => {
                console.log('景区列表', res.data)
                // 处理返回的数据，例如更新 scenicOptions 数组
                scenicOptions.value = res.data;
                console.log('景区列表', scenicOptions.value)
            })
            // 调用接口

            ElMessageBox({
                title: '更换景区',
                distinguishCancelAndClose: true,
                message: () => h('div', { style: { margin: '10px', width: '100px' } }, [
                    h(ElSelect, {
                        modelValue: scenicSelected.value,  // 绑定当前值
                        'onUpdate:modelValue': (val) => { scenicSelected.value = val }, // 更新值
                        style: { width: '150px', display: 'block' },
                        placeholder: '请选择景区',
                        onChange: (value) => {
                            scenicSelected.value = value
                        }
                    }, {
                        default: () => scenicOptions.value.map(option =>
                            h(ElOption, {
                                key: option.id,// 假设接口返回的数据结构中使用的是 'label' 字段而非 'name' 字段，这里将其修改为 'label'
                                label: option.name,
                                value: option.id
                            })
                        )
                    })
                ]),
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        if (!scenicSelected.value) {
                            ElMessage.error('请选择景区')
                            return
                        }
                        changeScenicApi({
                            id: row.id,
                            scenicId: scenicSelected.value
                        }).then(() => {
                            ElMessage.success(`成功将车辆 ${row.carCode} 更换到景区 ${scenicSelected.value}`)
                            getDataList()
                            done()
                        }).catch(error => {
                            ElMessage.error(`更换景区失败: ${error}`)
                        })
                    } else {
                        done()
                    }
                }
            })
            break
        case 'setCarStatus':
            ElMessageBox({
                title: '设置车辆状态',
                distinguishCancelAndClose: true,
                message: () => h('div', { style: { margin: '10px', width: '100px' } }, [
                    h(ElSelect, {
                        modelValue: runStatusSelected.value,
                        'onUpdate:modelValue': (val) => { runStatusSelected.value = val },
                        style: { width: '150px', display: 'block' },
                        placeholder: '请选择车辆状态',
                        onChange: (value) => {
                            carStatusSelected.value = value
                        }
                    }, {
                        default: () => carStatusOptions.map(option =>
                            h(ElOption, {
                                key: option.value,
                                label: option.label,
                                value: option.value
                            })
                        )
                    })
                ]),
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        if (carStatusSelected.value === undefined) {
                            ElMessage.error('请选择车辆状态')
                            return
                        }
                        setCarStatusApi({
                            id: row.id,
                            carStatus: carStatusSelected.value
                        }).then(() => {
                            ElMessage.success(`成功将车辆 ${row.carCode} 状态设置为 ${formatCarStatus(carStatusSelected.value)}`)
                            getDataList()
                            done()
                        }).catch(error => {
                            ElMessage.error(`设置车辆状态失败: ${error}`)
                        })
                    } else {
                        done()
                    }
                }
            })
            break
        case 'setRunStatus':
            ElMessageBox({
                title: '设置运行状态',
                distinguishCancelAndClose: true,
                message: () => h('div', { style: { margin: '10px', width: '100px' } }, [
                    h(ElSelect, {
                        style: { width: '150px', display: 'block' },
                        placeholder: '请选择运行状态',
                        onChange: (value) => {
                            runStatusSelected.value = value;
                        }
                    }, {
                        default: () => runStatusOptions.map(option =>
                            h(ElOption, {
                                key: option.value,
                                label: option.label,
                                value: option.value
                            })
                        )
                    })
                ]),
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        if (runStatusSelected.value === undefined) {
                            ElMessage.error('请选择运行状态');
                            return;
                        }
                        // setRunStatusApi({
                        //     carId: row.id,
                        //     status: runStatusSelected.value
                        // }).then(() => {
                        //     ElMessage.success(`成功将车辆 ${row.carCode} 运行状态设置为 ${runStatusSelected.value}`);
                        //     getDataList();
                        //     done();
                        // }).catch(error => {
                        //     ElMessage.error(`设置运行状态失败: ${error}`);
                        // });
                    } else {
                        done();
                    }
                }
            });
            break; // 注意这里添加了break

    }
}
// 添加响应式变量
const scenicSelected = ref()
const carStatusSelected = ref()
const runStatusSelected = ref()
// 在 API 文件中添加新接口



// 初始化
onMounted(() => {
    loadMap()
    getDataList()
    useSsScenicLabelApi().then(res => {
        scenicOptions.value = res.data;
    });
    // setInterval(loadMap, 10000);
})

// 使用CRUD钩子
const {
    getDataList,
    selectionChangeHandle,
    sizeChangeHandle,
    currentChangeHandle,
    deleteBatchHandle,
    downloadHandle,
    reset
} = useCrud(state)
</script>

<style scoped>
.layout-query,
.layout-table {
    margin-bottom: 15px;
}

/* 全局样式，确保下拉框宽度 */
.el-message-box__content .el-select {
    width: 100% !important;
    display: block !important;
}

/* 如果需要，可以调整下拉框的容器样式 */
.el-message-box__content {
    width: 100%;
}
</style>
